package app

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
	"time"
)

// Login 小程序登录
func Login(c *gin.Context) {
	DB := common.GetDB()
	openId := c.PostForm("openId")
	telephone := c.PostForm("telephone")

	if len(telephone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "手机号码不正确")
		return
	}

	var wxUser model.WxUser

	DB.Where("telephone = ?", telephone).First(&wxUser)

	if wxUser.ID != 0 {
		token, err := common.CreatToken(wxUser)
		if err != nil {
			response.Reponse(c, http.StatusOK, 500, nil, "token生成失败")
			return
		}
		if wxUser.OpenId == "" {
			DB.First(&wxUser).Update("open_id", openId)
			response.Reponse(c, http.StatusOK, 200, gin.H{"token": token}, "登录成功")
			return
		} else {
			if wxUser.OpenId != openId {
				response.Reponse(c, http.StatusOK, 422, nil, "绑定的微信号与当前微信不匹配")
				return

			} else {
				if wxUser.UserTime.After(wxUser.CreatedAt) {
					//更新用户登录时间
					DB.First(&wxUser).Update("updated_at", time.Now())
					//登录成功
					response.Reponse(c, http.StatusOK, 200, gin.H{"token": token}, "登录成功")
					return
				} else {
					response.Reponse(c, http.StatusOK, 422, nil, "会员时间过期！")
					return
				}

			}
		}
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "该用户不存在")
		return
	}
}
